/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2012  Lindsay Mathieson <lindsay.mathieson@kdemail.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/


#include "watchedthreaddata.h"
#include <qjson/parser.h>
#include <KDebug>
#include "settings.h"

const QString APIURL = "http://whirlpool.net.au/api/?output=json&key=";

QString WatchedThreadData::Summary::getText()
{
    if(nUnreadMsgs == 0)
        return "No threads with unread messages";

    QString text = QString("%1 unread message").arg(nUnreadMsgs);
    if (nUnreadMsgs > 1)
    {
        text += "s";
        if (nUnreadThreads > 1)
            text += QString(" in %1 threads").arg(nUnreadThreads);
    }

    return text;
}

WatchedThreadData::Summary WatchedThreadData::List::getSummary()
{
    WatchedThreadData::Summary summary;
    foreach(WatchedThreadData th, *this)
    {
        if (th.unread > 0)
        {
            summary.nUnreadThreads++;
            summary.nUnreadMsgs  += th.unread;
        }
    }

    return summary;
}

WatchedThreadData::List WatchedThreadData::parseJson(QByteArray& json)
{
    WatchedThreadData::List rc;

    // Parse the sucker
    QJson::Parser parser;

    bool ok;

    // json is a QString containing the data to convert
    QVariantMap	 result = parser.parse(json, &ok).toMap();

    if (! ok)
    {
        kDebug() << "Failed to parse json" << endl;
        return rc;
    }

    long userId = 0;
    QStringList apiKeys = Settings::api_key().split("-");
    if (apiKeys.count() > 0) {
        userId = apiKeys[0].toLong();
    }

    QVariantList qWatched = result["WATCHED"].toList();
    kDebug() << "Got " << qWatched.size() << " threads" << endl;
    foreach(QVariant qth, qWatched)
    {
        QVariantMap mth = qth.toMap();
        WatchedThreadData th;

        th.id= mth["ID"].toLongLong();
        th.title = mth["TITLE"].toString();
        th.replies = mth["REPLIES"].toInt();
        th.unread = mth["UNREAD"].toInt();
        th.lastRead = mth["LASTREAD"].toInt();
        th.lastPage = mth["LASTPAGE"].toInt();
        th.lastId = mth["LAST"].toMap()["ID"].toInt();
        th.lastName = mth["LAST"].toMap()["NAME"].toString();
        th.lastDate = mth["LAST_DATE"].toDateTime();
        if (Settings::ignore_own_posts() && userId > 0 && userId == th.lastId)
            th.unread = 0;
        if (th.unread == 0)
            continue;

        rc.append(th);
    }

    return rc;
}

QUrl WatchedThreadData::getWatchedUrl(bool unreadOnly)
{
    QString url = APIURL + Settings::api_key() + "&get=watched&watchedmode=" + (unreadOnly ? "0" : "1");

    return QUrl(url);
}

QUrl WatchedThreadData::getOpenUrl() const
{
    QString url =
        QString("http://forums.whirlpool.net.au/forum-replies.cfm?t=%1&p=%2&#r%3")
        .arg(id).arg(lastPage).arg(lastRead);

    return QUrl(url);
}

QUrl WatchedThreadData::getMarkReadUrl(bool autoHide) const
{
    QString url = APIURL + Settings::api_key() + "&watchedread=" + QString("%1").arg(id);
    if (autoHide)
        url += "&autohide";


    return QUrl(url);
}

bool WatchedThreadData::NewMessagesInW2(const List& w1, const List& w2)
{
    // Does w2 have more threads
    if (w2.size() > w1.size())
        return true;

    // Does w2 have threads not in w1
    foreach(WatchedThreadData th2, w2)
    {
        // Find thread in w1
        bool found = false;
        foreach(WatchedThreadData th1, w1)
        {
            if (th1.id == th2.id)
            {
                // does th2 have more new messages that th1
                if (th2.replies > th1.replies)
                    return true;

                found = true;
                break;
            }
        }
        if (! found)
            return true;
    }

    return false;
}
